package com.bawei.day12_broadcastrecevier;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

/**
 广播接受者
 1。自定义类继承BroadCastRecevier，重写onRecevie
 2。注册广播：（1）静态注册（清单文件）（2）动态注册（使用java代码）+解除注册
 广播发送者：sendBroadcast(intent);

***动态注册和静态注册的区别：
 动态注册：生命周期随着activity，灵活控制注册和取消
 静态注册：生命周期不跟随activity，即使app关闭也是一直存在，非必要情况下不建议采用静态注册，浪费资源

 */
public class Main2Activity extends AppCompatActivity {
    private MyRecevicer myRecevicer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //动态注册
        myRecevicer = new MyRecevicer();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.yaotianxue3");
        intentFilter.addAction("com.bawei.yaotianxue4");
        registerReceiver(myRecevicer,intentFilter);


        findViewById(R.id.bt_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.bawei.yaotianxue3");
                Bundle bundle = new Bundle();
                bundle.putString("message","我是动态注册333");
                intent.putExtra("data",bundle);
                sendBroadcast(intent);
            }
        });
        findViewById(R.id.bt_send2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.bawei.yaotianxue4");
                Bundle bundle = new Bundle();
                bundle.putString("message","我是动态注册44444");
                intent.putExtra("data",bundle);
                sendBroadcast(intent);
            }
        });

    }
    //解除注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myRecevicer);
    }

    class MyRecevicer extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.yaotianxue3".equals(intent.getAction())){
                //获得数据
                Bundle data = intent.getBundleExtra("data");
                String message = data.getString("message");
                Toast.makeText(context, ""+message, Toast.LENGTH_SHORT).show();
            }else  if("com.bawei.yaotianxue4".equals(intent.getAction())){
                //获得数据
                Bundle data = intent.getBundleExtra("data");
                String message = data.getString("message");
                Toast.makeText(context, ""+message, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
